<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
	xmlns:mywidgets="http://xmlns.jcp.org/jsf/composite/widgets"
	xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions"
	xmlns:pt="http://xmlns.jcp.org/jsf/passthrough">

<ui:composition template="/templates/photoTemplate.xhtml">

	<ui:define name="title">
		#{i18N.getTrans('TextAndTranslation')}	
	</ui:define>

	<ui:define name="body">

		<h1>#{i18N.getTrans('TextAndTranslation')}</h1>

		<script>
		$(function() {
			$(document).tooltip({
				track: true
			});

			$('form:first *:input[type!=hidden]:first').focus();
		});
		</script>


		<h:form id="listOfTextUnitsForm">

			<h:inputText autocomplete="true" style="width: 300px"
				value="#{textController.searchFilter}"
				pt:placeholder="Token or text in English" pt:autofocus="true"
				title="Search by token or text in English">
				<f:ajax event="keyup" execute="@this" render="textTable" />
			</h:inputText>

			<p class="betweenSections" />

			<h:panelGroup id="searchListPanel">

				<h:dataTable id="textTable"
					value="#{textController.findTextUnitsByString()}" var="textUnit"
					styleClass="data-table" headerClass="table-header"
					rowClasses="table-odd-row,table-even-row">

					<h:column>
						<!-- column header -->
						<f:facet name="header">Action</f:facet>
						<!-- row record -->
						<h:commandButton value="edit" styleClass="mini"
							action="#{textController.loadTextDetail()}">
							<f:param name="id" value="#{textUnit.id}" />
							<f:ajax execute="@form"
								render=":textUnitForm:detailGroup :translationsForm:transGroup" />
						</h:commandButton>
						<h:commandButton value="delete" styleClass="mini"
							action="#{textController.deleteText()}">
							<f:param name="id" value="#{textUnit.id}" />
							<f:ajax execute="@this" render="@form :textUnitForm:detailGroup :translationsForm:transGroup" />
						</h:commandButton>
					</h:column>

					<h:column sortBy="#{textUnit.token}"
						filterExpression="#{empty filterValue or fn:startsWith(textUnit.token, filterValue)}"
						filterValue="#{textController.searchFilter}">
						<f:facet name="header">Token</f:facet>
						<h:outputText value="#{textUnit.token}" styleClass="textToken"/> - 
						<h:panelGroup rendered="#{textUnit.translation.size() == 0}">
							<span style="color:red">no translations saved</span>
						</h:panelGroup>
						<h:panelGroup rendered="#{textUnit.translation.size() != 0}">
							#{textUnit.translation.size()} translation(s)
						</h:panelGroup>
						
					</h:column>

					<h:column>
						<!-- column header -->
						<f:facet name="header">Default Text</f:facet>
						<!-- row record -->
    					#{textUnit.defaultText}
    			</h:column>
				</h:dataTable>
			</h:panelGroup>

		</h:form>


		<h2>Text unit</h2>

		<h:form id="textUnitForm">

			<h:panelGroup id="detailGroup">
				<h:inputHidden id="id" value="#{textController.id}" />
				<table
					title="#{textController.translations.size()} distinct translations available (others might be inherited).">
					<tr>
						<td title="Token format: [context].[category].[token]"><label
							for="token">Token</label> <h:inputText id="token"
								value="#{textController.token}" required="true"
								requiredMessage="Please insert a token string for this new translation." pt:placeholder="Enter a text token!"  />
								
						</td>
						<td><label for="text">Default Text</label> <h:inputTextarea
								id="text" value="#{textController.text}" required="true"
								requiredMessage="Please insert a default text translation."
								cols="50" rows="4"  pt:placeholder="Enter a default translation, which shows when no locale-specific translation is available."  /></td>
					</tr>
				</table>

				<h:commandButton value="save text"
					action="#{textController.saveText()}"
					title="If this is a new text, it will be created. Otherwise it is simply updated.">
					<f:ajax execute="@form"
						render=":listOfTextUnitsForm:searchListPanel :translationsForm:transGroup" />
				</h:commandButton>

			</h:panelGroup>

		</h:form>

		<p class="betweenSections" />

		<h2>Translations</h2>

		<h:form id="translationsForm">
			<h:inputHidden id="textId" value="#{textController.id}" />
			<h:panelGroup id="transGroup">

				<table>
					<tbody>

						<ui:repeat var="trans" varStatus="status"
							value="#{translationController.getAllTranslationsByTextId(textController.id)}">
							<tr>
								<h:panelGroup
									rendered="#{not empty trans.locale.country.countryCode}">
									<td style="vertical-align: middle; white-space: wrap;">
										#{trans.locale.localeCode}
									</td>
								</h:panelGroup>

								<h:panelGroup
									rendered="#{empty trans.locale.country.countryCode}">
									<td style="vertical-align: middle; white-space: wrap;"
										title="#{trans.locale.language.nativeLanguageName}">
										#{trans.locale.language.languageCode}</td>
								</h:panelGroup>

								<td style="white-space: nowrap; vertical-align: middle">
								<h:inputTextarea
										styleClass="translationTextArea" id="translation"
										value="#{trans.translation}" cols="80" rows="1">
									</h:inputTextarea> 
									<!-- update saving progress -->
									<span class="transUpdate"></span>
									<h:panelGroup rendered="#{trans.translationFromParent}"
										style="display: inline;">
												(parental translation)										
									</h:panelGroup>
								
								
								
								</td>
							</tr>
						</ui:repeat>
					</tbody>
				</table>

				<script>
					$( ".translationTextArea" ).on("change", 
							(function() {
								var newTransElement = $(this);	
								var textId = $("input[id*=':id']").val();	
								var localeCode = newTransElement.closest('td').prev().html().trim().replace(/ /g,'');					
 								updateTranslation(newTransElement, textId, localeCode, newTransElement.val());							
						
							})
					);

					var updateTranslation = function (domElement, textId, localeCode, translation){
						var URL_BASIC = MAIN_REST_URL + '/i18n/translation/';
						var requestURL = URL_BASIC + textId + "/" + localeCode;
						
						$.ajax({
						    url: requestURL,
						    type: 'PUT',
						    dataType : 'xml',
// 						    data: JSON.stringify(translation )
 						    data: translation,						    
						    beforeSend: function( xhr ) {
						    	$("body").toggleClass("wait");
						    	domElement.next(".transUpdate").show();
						    	domElement.next(".transUpdate").html("Saving update ...");
						    }			    
						})
						.fail(function() {
							alert( "Failed to update the translation." );
						})
						.always(function() {
							$("body").toggleClass("wait");
							domElement.next(".transUpdate").html("Saved successfully.");
							
							setTimeout(
								function() {
						    		$(domElement).next(".transUpdate").fadeOut(1000);
						    	}, 
						    	2000); 
						})
						;
					};

					// Now, scroll down to edit the records.
					var anchorObj = document.getElementById('textUnitForm:detailGroup'); 
				    window.scrollTo(0, anchorObj.offsetTop);

				</script>
			</h:panelGroup>
		</h:form>

	</ui:define>
</ui:composition>
</html>
